package model.factories.misc;

import java.util.Map;
import java.util.Scanner;
import java.util.regex.Pattern;
import model.Interpreter;
import model.SyntaxErrorException;
import model.commands.Command;
import model.factories.CommandFactory;


/**
 * A factory used to build ParenthesisCommand objects
 * 
 * @author Erick Gonzalez
 * @author JLongley
 */
public class ParenthesisCommandFactory extends CommandFactory {
    /**
     * Pattern that matches Lists of commands in brackets
     */
    public static final Pattern PARENTHESIS_PATTERN = Pattern.compile("\\(");

    private static final String CLOSE_PARENTHESIS = "\\)";

    /**
     * 
     * @param interpreter an Interpreter
     */
    public ParenthesisCommandFactory (Interpreter interpreter) { 
        super(interpreter);
    }

    @Override
    public Command createCommand (Scanner commandReader,
                                  Map<String, Integer> variables) throws SyntaxErrorException {
        Interpreter interpreter = getInterpreter();

        // read the open bracket
        commandReader.next();

        // create a command with the default number of arguments. e.g. SUM 1 2
        Command myCommand = interpreter.parse(commandReader, variables);

        // while there isn't a closing parenthesis next, keep adding additional arguments to the
        // command
        while (!commandReader.hasNext(CLOSE_PARENTHESIS)) {
            Command arg = interpreter.parse(commandReader, variables);
            myCommand.getArguments().add(arg);
        }

        // remove the extra close bracket
        commandReader.next();
        return myCommand;
    }

    @Override
    public Pattern patternToMatch () {
        return PARENTHESIS_PATTERN;
    }
}
